package org.xxpay.pay.channel.hmapay;

import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.xxpay.pay.ctrl.common.BaseController;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.TreeMap;

@Controller
public class HmapayController extends BaseController {

    @RequestMapping("/api/hmapay/hmapay_alipay.htm")
    public String toPay(HttpServletRequest request, ModelMap model) throws ServletException, IOException {
        JSONObject po = getJsonParam(request);
        // https://qr.alipay.com/fkx04112akzpulwo9pvye74?t=1541681073413
        String pid = getString(po, "pid");
        String out_trade_no = getString(po, "out_trade_no");
        String money = getString(po, "money");
        String type = getString(po, "type");
        String userip = getString(po, "userip");
        String userid = getString(po, "userid");
        String notify_url = getString(po, "notify_url");
        String return_url = getString(po, "return_url");
        String sign = getString(po, "sign");
        String toPayUrl = getString(po, "toPayUrl");

        TreeMap<String, String> paramMap = new TreeMap<>();
        // 接口类型
        paramMap.put("pid", pid);
        paramMap.put("out_trade_no", out_trade_no);
        paramMap.put("money", money);
        paramMap.put("type", type);
        paramMap.put("userip", userip);
        paramMap.put("userid", userid);
        paramMap.put("notify_url", notify_url);  // 回调地址
        paramMap.put("return_url", return_url);
        paramMap.put("sign", sign);

        StringBuffer payForm = new StringBuffer();
        payForm.append("<form style=\"display: none\" action=\""+ toPayUrl +"\" method=\"post\">");
        paramMap.keySet().stream().forEach(key ->
                payForm.append("<input type=\"text\" name=\""+key+"\" value=\""+paramMap.get(key)+"\">")
        );
        payForm.append("<input type=\"submit\" value=\"立即支付\" style=\"display:none\" >");
        payForm.append("</form>");
        payForm.append("<script>document.forms[0].submit();</script>");
        model.put("payForm", payForm);

        return "payment/hmapay/hmapay_alipay";
    }
}
